"""
Utility function to parse user input and determine the mode.
"""
import json

def parse_input(user_input, mode):
    """
    Parse user input based on the explicitly specified mode.
    
    Args:
        user_input: Raw input from user (str or dict)
        mode: Explicitly specified mode ("chat" for free conversation or "check" for correction)
        
    Returns:
        parsed_content: Parsed content (dict for correction mode, str for chat mode)
    """
    # In check (correction) mode, input must be valid JSON with required structure
    if mode == "check":
        required_keys = ["compliance_type", "title", "description", "guide", "inspector", "risk_level", "compliance_status"]
        
        # If input is already a dict, validate it
        if isinstance(user_input, dict):
            if all(key in user_input for key in required_keys):
                return user_input
            else:
                raise ValueError("Invalid JSON structure for check mode. Required keys missing.")
        
        # If input is a string, try to parse as JSON
        elif isinstance(user_input, str):
            try:
                parsed_json = json.loads(user_input)
                if all(key in parsed_json for key in required_keys):
                    return parsed_json
                else:
                    raise ValueError("Invalid JSON structure for check mode. Required keys missing.")
            except json.JSONDecodeError:
                raise ValueError("Invalid JSON input for check mode. Input must be valid JSON.")
    
    # In chat (free conversation) mode, return input as is
    elif mode == "chat":
        # If it's a dict, convert to string for consistency in chat mode
        if isinstance(user_input, dict):
            return json.dumps(user_input)
        return user_input
    
    # Invalid mode
    else:
        raise ValueError("Invalid mode. Mode must be 'chat' or 'check'.")

if __name__ == "__main__":
    # Test with chat mode
    test_input1 = "Hello, how are you?"
    try:
        parsed_content1 = parse_input(test_input1, "chat")
        print(f"Chat mode - Content: {parsed_content1}")
    except ValueError as e:
        print(f"Error: {e}")
    
    # Test with check mode using valid input
    test_input2 = {
        "compliance_type": "风险项",
        "title": "测试标题",
        "description": "测试描述",
        "guide": "测试指引",
        "inspector": "测试检查人员",
        "risk_level": "高",
        "compliance_status": "不满足"
    }
    try:
        parsed_content2 = parse_input(test_input2, "check")
        print(f"Check mode - Content: {parsed_content2}")
    except ValueError as e:
        print(f"Error: {e}")
    
    # Test with check mode using invalid input
    test_input3 = "This is not JSON"
    try:
        parsed_content3 = parse_input(test_input3, "check")
        print(f"Check mode - Content: {parsed_content3}")
    except ValueError as e:
        print(f"Error: {e}")
        
    # Test with invalid mode
    try:
        parsed_content4 = parse_input(test_input1, "invalid_mode")
        print(f"Invalid mode - Content: {parsed_content4}")
    except ValueError as e:
        print(f"Error: {e}")
